import axios from 'axios'
import {Message} from 'iview'
import config from '@/config'
// import { Spin } from 'iview'
import {getToken, setToken} from '@/libs/util'

import miniLoginForm from '../view/components/mini-login-form/mini-login-form'



const LOGIN_PAGE_NAME = 'login'
class HttpRequest {

    constructor(baseUrl = baseURL) {
        this.baseUrl = baseUrl
        this.queue = {}
    }

    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl,
            headers: {
                token: getToken()
            }
        }
        return config
    }

    destroy(url) {
        delete this.queue[url]
        if (!Object.keys(this.queue).length) {
            // Spin.hide()
        }
    }

    interceptors(instance, url) {
        // 请求拦截
        instance.interceptors.request.use(config => {
            // 添加全局的loading...
            if (!Object.keys(this.queue).length) {
                // Spin.show() // 不建议开启，因为界面不友好
            }
            this.queue[url] = true
            return config
        }, error => {
            return Promise.reject(error)
        })
        // 响应拦截
        instance.interceptors.response.use(res => {
            Message.destroy()
            if (res.data.hasOwnProperty('code')) {
                let data = res.data
                // console.log(data.code)
                if (data.code === 10002) {
                    for (let a in data.msg) {
                        Message.error(data.msg[a]);
                        break;
                    }
                } else if (data.code === 10001) {
                    Message.error(data.msg)
                    console.log(res)
                    if (res.request.responseURL.indexOf('token') < 0)
                    setTimeout(() => {
                        window.location.href = '/login'
                    },1800)
                } else if (data.code > 0) {
                        Message.error(data.msg)
                }
            } else {
                Message.error('系统错误哦！')
            }
            // this.destroy(url)
            // const {data, status} = res
            return res.data
        }, error => {
            this.destroy(url)
            Message.error('网络错误！')
            return Promise.reject(error)
        })
    }

    request(options) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        if (config.debug) {
            if (options.url.indexOf('?') > 0) {
                options.url = options.url + '&' + config.debugMsg

            } else {
                options.url = options.url + '?' + config.debugMsg
            }
        }
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

export default HttpRequest
